package com.hmdp.utils;

import cn.hutool.core.lang.Assert;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @author walls1717
 * @since 2022/7/31
 **/
@Component
public class RedisIdWorker {

    /**
     * 指定时间秒数 20220101000
     */
    private static final long BEGIN_TIMESTAMP = 1640995200L;

    /**
     * 时间戳前移位数
     */
    private static final long COUNT_BITS = 32L;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public long nextId(String keyPrefix) {
        // 获取当前时间并转化为秒
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        // 当前时间秒-指定时间秒生成时间戳
        long timestamp = nowSecond - BEGIN_TIMESTAMP;

        // 格式化当前日期作为key，统计每日订单量
        String date = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        // Redis自增长，统计id生成数量
        Long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
        assert count != null;
        // 利用时间戳与Redis自增长形成id
        return timestamp << 32 | count;
    }

    public static void main(String[] args) {
        LocalDateTime time = LocalDateTime.of(2022, 1, 1, 0, 0, 0);
        long second = time.toEpochSecond(ZoneOffset.UTC);
        System.out.println("second = " + second);
    }
}
